package com.flow.demo.module.gd.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import static com.flow.demo.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.flow.demo.module.infra.enums.ErrorCodeConstants.FILE_FAIL;
import static com.flow.demo.module.infra.enums.ErrorCodeConstants.FILE_NOT_EXISTS;

public class FileUtils {

    public static String upLoadFile(MultipartFile file, String path) {

        if (file.isEmpty()) {
            throw exception(FILE_NOT_EXISTS);
        }
        File dest = new File(path);
        if (!dest.exists()) { //判断文件目录是否存在
            dest.mkdir();
        }
        String fileName = file.getOriginalFilename();
        // 取得文件的后缀名。
        String newFileName = System.currentTimeMillis() +"_"+fileName;
        File newFile = new File(path + "/" + newFileName);
        try {
            file.transferTo(newFile); //保存文件
            return newFileName;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw exception(FILE_FAIL);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw exception(FILE_FAIL);

        }
    }

    public static void compressImage(File inputImage, File outputImage) throws IOException {
        // 读取原始图片
        BufferedImage sourceImage = ImageIO.read(inputImage);

        // 获取原始图片的宽度和高度
        int width = sourceImage.getWidth();
        int height = sourceImage.getHeight();

        if (width > 800) { // 如果宽度超过800，则进行压缩
            // 计算压缩比例
            double scaleFactor = 800.0 / width;

            // 计算压缩后的宽度和高度
            int compressedWidth = 800;
            int compressedHeight = (int) (height * scaleFactor);

            // 创建缩放后的图片对象
            Image compressedImage = sourceImage.getScaledInstance(compressedWidth, compressedHeight, Image.SCALE_SMOOTH);

            // 创建BufferedImage对象，并绘制压缩后的图片
            BufferedImage outputBufferedImage = new BufferedImage(compressedWidth, compressedHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = outputBufferedImage.createGraphics();
            graphics.drawImage(compressedImage, 0, 0, null);
            graphics.dispose();

            // 写入输出文件
            // 获取文件扩展名，如 abc.de.jpg，就获取 jpg
            String extensionName = inputImage.getName().substring(inputImage.getName().lastIndexOf(".") + 1);
            ImageIO.write(outputBufferedImage, extensionName, outputImage);
            System.out.println("图片压缩成功！");
        } else { // 如果宽度不超过1920，则直接复制
            System.out.println("图片宽度未超过800，不进行压缩！");
        }
    }
}
